Ext.define('Ext.ux.desktop.applications.Openinghours', {
	extend: 'Ext.ux.desktop.applications.AbstractApplication',

	id:'openinghours-app-window',
	title: 'Opening Hours',
	iCls: 'icon-openinghours',
	//pageSize: 20,
	//grid: null,
	//dialogs: {},
	scriptURL: "/admin/openinghours/",
	doctorURL: "/admin/doctors/",
	modelName: 'Openinghours',
	doctorModelName: 'OHDoctor',

	timeConvert: function(v,record){
		return v.split(':',2).join(':');
	},
	//store: null,
	/*
	 init: function(){
	 this.createWindow();
	 },
	 */
	createModel: function(){
		Ext.define(this.modelName, {
			extend: 'Ext.data.Model',
			fields: [
				{name: 'open_id', type: 'int'},
				{name: 'doctor_id', type: 'int'},
				{name: 'day',  type: 'string'},
				{name: 'begin_time',  type: 'string', convert: this.timeConvert},
				{name: 'end_time', type: 'string', convert: this.timeConvert},
				{name: 'cabinet', type: 'int'}
			]
		});

		Ext.define(this.doctorModelName, {
			extend: 'Ext.data.Model',
			fields: [
				{name: 'id', type: 'int'},
				{name: 'DName',  type: 'string'}
			]
		});
	},

	createStore: function(){
		this.store =  new Ext.data.Store({
			model: this.modelName,
			proxy: {
				type: 'ajax',
				url : this.scriptURL + 'index',
				reader: {
					type: 'json',
					root: 'data',
					idProperty: 'open_id',
					totalProperty: 'total'
				}
			},
			pageSize: this.pageSize,
			remoteSort: false,
			autoLoad: true
		});
		this.doctorStore = new Ext.data.Store({
			model: this.doctorModelName,
			proxy: {
				type: 'ajax',
				url : this.doctorURL+"search",
				reader: {
					type: 'json',
					root: 'data',
					idProperty: 'id',
					totalProperty: 'total'
				}
			},
			pageSize: this.pageSize,
			remoteSort: true,
			autoLoad: true
		});
	},

	createWindow: function(){
		var _this = this;
		this.createModel();
		this.createStore();
		var window = Ext.create('Ext.window.Window',{
			id: this.id,
			title: this.title,
			iconCls: this.iCls,
			width:400,
			height:400,
			shim:false,
			animCollapse:false,
			constrainHeader:true,
			maximizable: false,
			layout: 'fit',
			items: [
				{
					xtype: 'grid',
					border: false,
					store: this.store,
					dockedItems: [{
						xtype: 'toolbar',
						dock: 'top',
						id: this.id+'-grid-top-buttons',
						items: [
							{
								text: 'Add',
								//iconCls: 'ico-add',
								handler: function(){
									var d = this.getSubjectEditDialog();
									d.setMode('add');
									d.show({});
								},
								scope: this,
								disabled: false,
								btnName: 'add'
							},{
								text: 'Edit',
								//iconCls: 'ico-edit',
								handler: function(){
									this.doRowAction('editSubject');
								},
								scope: this,
								disabled: true,
								btnName: 'edit'
							},{
								text: 'Delete',
								//iconCls: 'ico-delete',
								handler: function(){
									this.doRowAction('deleteSubject');
								},
								scope: this,
								disabled: true,
								btnName: 'delete'
							}
						]
					}],
					columns:[
						{
							text: 'Doctor',
							dataIndex: 'doctor_id'
						},
						{
							text: 'Day',
							dataIndex: 'day'
						},
						{
							text: 'Start time',
							dataIndex: 'begin_time'
						},
						{
							text: 'End time',
							dataIndex: 'end_time'
						},
						{
							text: 'Cabinet No',
							dataIndex: 'cabinet'
						}
					],
					selModel: new Ext.selection.RowModel({
						mode: 'single',
						listeners: {
							selectionchange: function(sm) {
								var sc = sm.getCount();
								/**
								 * @todo delete sr variable
								 */
								var sr = sm.getLastSelected();
								var bs = {
									'add': false,
									'edit': true,
									'delete': true
								};
								if (sc == 1){
									bs['edit'] = false;
									bs['delete'] = false;
								}
								this.setActiveButtons(this.grid.getDockedComponent(this.id+'-grid-top-buttons'),bs);
							},
							scope: this
						}
					}),
					forceFit:true,
					bbar: new Ext.PagingToolbar({
						pageSize: this.pageSize,
						store: this.store,
						displayInfo: true
					}),
					loadMask: true,
					listeners: {
						render: function(g) {
							this.grid = g;
						},
						scope: this
					}
				}
			]
		});
		window.show();
	},

	createEditDialog: function(){
		var dialogWindow = Ext.create('Ext.ux.desktop.modules.EditDialog',{
			id: 'openinghours-app-edit-dialog',
			iconCls: this.iCls,
			items: {
				xtype: "form",
				bodyBorder: false,
				border: false,
				baseCls: "x-plain",
				style: "padding: 5px;",
				labelWidth: 110,
				url: '/admin/openinghours/edit',
				items: [
					{xtype: "hidden", name: "open_id", dataIndex: "open_id"},
					{
						xtype: 'combo',
						allowBlank: false,
						anchor: '99%',
						queryParam: 'query',
						fieldLabel: 'Doctor',
						name: 'doctor_id',
						dataIndex: 'doctor_id',
						hiddenName: 'doctor_id',
						triggerAction: 'all',
						valueField: 'id',
						displayField: 'DName',
						store: this.doctorStore,
						value: '',
						//mode: 'local',
						lazyInit: false,
						forceSelection: true,
						emptyText: 'enter doctor name',
						autoScroll: true,
						minChars: 1,
						editable: true
					},
					{
						xtype: 'combo',
						fieldLabel: 'Day',
						name: 'day',
						dataIndex: 'day',
						inputField: 'day',
						hiddenName: 'day',
						displayField: 'name',
						valueField: 'value',
						anchor: '99%',
						mode: 'local',
						triggerAction: 'all',
						editable: false,
						value: 'monday',
						store: new Ext.data.SimpleStore({
							fields: ['name', 'value'],
							data: [
								['monday', 'Monday'],
								['tuesday', 'Tuesday'],
								['wednesday', 'Wednesday'],
								['thursday', 'Thursday'],
								['friday', 'Friday'],
								['saturday', 'Saturday'],
								['sunday', 'Sunday']
							]
						}),
						allowBlank: false
					},
					{xtype: "timefield", fieldLabel: "Start Time"+"*", name: "begin_time", anchor: "99%", allowBlank: false, minValue: '08:00', maxValue: '20:00', increment: 30, format: "H:i"},
					{xtype: "timefield", fieldLabel: "End Time"+"*", name: "end_time", anchor: "99%", allowBlank: false, minValue: '08:00', maxValue: '20:00', increment: 30, format: "H:i"},
					{xtype: "numberfield", fieldLabel: "Cabinet No"+"*", name: "cabinet", anchor: "99%", minValue: 1, maxValue: 999, allowBlank: false}
				]
			},
			modeTitles: {
				add: 'Add Opening Hours',
				edit: 'Edit Opening Hours'
			},
			modeUrls: {
				add: this.scriptURL+'edit',
				edit: this.scriptURL+'edit'
			},
			listeners: {
				successSend: function(){
					if(this.grid) {
						this.grid.getStore().load();
					};
				},
				scope:this
			}
		});
		return dialogWindow;
	},

	doRowAction: function(action) {
		if (!action || !this.row_actions[action]) return false;
		var g = this.grid;
		if (!g) return false;
		var sm = g.getSelectionModel();
		var d = sm.getLastSelected();
		if (d && d.data) {
			this.row_actions[action].apply(this, [d.data, sm]);
		}
		return false;
	},

	row_actions: {
		editSubject:function(data, sm){
			var d = this.getSubjectEditDialog();
			d.setMode('edit');
			d.show(data);
		},

		deleteSubject:function(data, sm){
			var o = {
				sm: sm,
				grid: this.grid,
				url: this.scriptURL + 'delete',
				id_field: 'open_id'
			};
			Ext.applyIf(o, this.confirmation_obj);
			Ext.MessageBox.confirm('?','Do you really want to delete this opening hour(s)?', o.onAccept, o);
		}
	},

	getSubjectEditDialog:function(){
		if (!this.dialogs['editHours']) {
			this.dialogs['editHours'] = this.createEditDialog();
		};
		return this.dialogs['editHours'];
	}
});